package com.example.leaderapplication.View.Activity;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.example.leaderapplication.Base.BaseActivity;
import com.example.leaderapplication.Base.BaseConfig;
import com.example.leaderapplication.Bean.UserInfo;
import com.example.leaderapplication.R;
import com.example.leaderapplication.Utils.SPUtil;
import com.example.leaderapplication.Utils.ToastUtil;

public class CompreDisplayActivity extends BaseActivity {
    WebView mWebView;
    TextView tvClose;
    TextView centertext;
    private TextView tvBack;

    // H5 的引入
    private String productOnlyNo;
    private String webviewurl;
    private String path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int setLayoutId() {
        return R.layout.activity_compre_display;
    }

    @Override
    protected void initView() {

        // 获取网页传递过来的数据
        Intent intent = getIntent();
        path = intent.getStringExtra("Path");

        mWebView = (WebView) findViewById(R.id.compre_webview);
        tvClose = (TextView) findViewById(R.id.tv_close);
        tvBack = (TextView) findViewById(R.id.tv_back);
        centertext = (TextView) findViewById(R.id.centertext);
    }

    @Override
    protected void doSomeThing() {
        initWebView();

        tvClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setAllowFileAccess(true); //设置可以访问文件
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        mWebView.getSettings().setLoadsImagesAutomatically(true); //支持自动加载图片
        mWebView.getSettings().setBlockNetworkImage(false);//解决图片不显示
        mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.getSettings().setDefaultTextEncodingName("utf-8");//设置编码格式

        // 这是h5 交互
        mWebView.addJavascriptInterface(new schedule(), "booking");
        mWebView.addJavascriptInterface(new noLogin(), "noLogin");

        mWebView.getSettings().setAppCacheEnabled(true);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                centertext.setText(view.getTitle());

                String token;
                token = (String) SPUtil.get(CompreDisplayActivity.this, BaseConfig.ACCESS_TOKEN, "");

                String method = "javascript:getToken(\"" + token + "\")";
                mWebView.loadUrl(method);

            }

            @Override
            public void onLoadResource(WebView view, String url) {
                webviewurl = view.getUrl();
                super.onLoadResource(view, url);
            }


            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                try {
                    //iosLoadDialog.show();
                } catch (Exception e) {
                    Log.e("erro", Log.getStackTraceString(e));
                }
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url == null)
                    return false;
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    view.loadUrl(url);
                    return false;
                } else {
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        startActivity(intent);
                    } catch (Exception e) {
//                    ToastUtils.showShort("暂无应用打开此链接");
                    }
                    return true;
                }

            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();// 接受所有网站的证书
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }

        });

        // 这里 做页面跳转
        String onlineUrl = path;
//        String onlineUrl = BaseConfig.WEB_Base_URL + "#/pages/comprehensiveDisplay/comprehensiveDisplay";
//        String onlineUrl = "http://192.168.20.58:8081/#/pages/comprehensiveDisplay/comprehensiveDisplay";
        mWebView.loadUrl(onlineUrl);
    }

    private final class schedule {
        /**
         * 注意这里的@JavascriptInterface注解， target是4.2以上都需要添加这个注解，否则无法调用
         *
         * @param text
         */
        @JavascriptInterface
        public void schedule(String text, String businessOrgId, String destinationID, String destinationType) {

            //  这个地方  验证用户是否登入， 如果登入那么就去跳转页面
//            if (userInfo != null) {
//                productOnlyNo = text;
//            } else {
//                Intent intent = new Intent(CompreDisplayActivity.this, LoginActivity.class);
//                startActivity(intent);
//            }

        }

    }

    @SuppressWarnings("unused")
    private final class noLogin {
        /**
         * 注意这里的@JavascriptInterface注解， target是4.2以上都需要添加这个注解，否则无法调用
         */
        @JavascriptInterface
        public void noLogin(String text) {
            // ToastUtil.shortToast(OrderDetailsWebActivity.this,orderBatchId);
            ToastUtil.showToast("用户登录失效");
        }

    }

}
